<template>
	<div class='content-box'>
		<!--使用draggable组件-->
		<div class="content">
			<div class="left-box">
				<div class='left-item' v-for='(item,index) in leftArr' :key='index'> 
					<div class='title'>
						<svg t="1731396109399" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5230" data-spm-anchor-id="a313x.search_index.0.i2.7cf23a81oE6eUC" width="32" height="32"><path d="M512 7.68L75.264 259.84v504.32L512 1016.32l436.736-252.16v-504.32z m375.296 720.9984L512 945.3568l-375.296-216.6784V295.3216L512 78.6432l375.296 216.6784z" p-id="5231" fill="#666666"></path><path d="M318.5664 336.896l-30.72 53.248L481.28 501.8112V711.68h61.44V501.8112l193.4336-111.6672-30.72-53.248L512 448.6144 318.5664 336.896z" p-id="5232" fill="#666666"></path></svg>
					  <span>{{ item.title }}</span>
					</div>
					<draggable :clone="cloneItem" v-model="item.data" @end="onEnd" :options="{group:{name:'site',pull:'clone',put:false},sort: false}" animation="300">
						<transition-group>
							<div class='item' @click='handleLeftItems(items)' v-for='(items,indexs) in item.data' :key='indexs+1'>
								<img :src="require('@/assets/ico/'+items.type+'.svg')"/>
								<span>{{ items.name }}</span>
							</div>
						</transition-group>
					</draggable>
				</div>
			</div>
			<!-- 不要在<transition group>子节点上使用v-for index作为键，这与不使用键相同。index+1解决此问题 -->
			<div class="center-box">
				<div class="preview-box" v-if='arr.length>0' @click='submit(2)'>预览问卷</div>
				<draggable v-model='arr' :options="{group:{name:'site',pull:true,put:true},sort: true}" animation="300">
					<transition-group :style="style">
						<div class='center-item' :class='{"active-item":editIndex===index}' @click='handleCenterItems(item,index)' 
						  v-for="(item,index) in arr" :key='index+1'>
							<div class='item-setup' :class='{"active-setup":editIndex===index}'>
								<el-button @click.stop='copyItem(item)' size='mini' plain type="primary" icon="el-icon-document-copy" circle></el-button>
								<el-button @click.stop='deleteItem(index)' size='mini' plain type="danger" icon="el-icon-delete" circle></el-button>
							</div>
							<div class='title-box'>
								<div class='title'>
								  <span>
									  {{index+1}}、{{item.name}}
										<span v-if='item.type=="image"'>，0/{{item.maxNum||1}}</span>
									</span>
								  <span v-if='item.type!=="desc"'>{{ item.isAnswer?'(必填)':'(选填)' }}</span>
								</div>
								<i style='cursor: pointer;color:#999' @click.stop='handleCenterItems(item,index)' class="el-icon-edit"></i>
							</div>
							<div class='fill-box' v-if='item.type=="fill"'>
								<div class='input-box' style='margin-top: 10px;' v-for='(items,indexs) in item.field' :key='indexs'>请输入</div>
							</div>
							<div class='input-box' v-else-if='item.type=="textarea"' style='height: 72px'>请输入</div>
							<div class='input-box' v-else-if='item.common=="input"&&item.type!=="textarea"&&item.type!=="fill"'>请输入</div>
						  <div class='upload-img' v-else-if='item.type=="image"'>＋</div>
						  <div class='upload-file' v-else-if='item.type=="file"'>上传文件</div>
						  <div class='upload-sign' v-else-if='item.type=="signature"'>点击手写您的签名</div>
						  <div class='checkbox-box' v-else-if='item.type=="radio"||item.type=="checkbox"'>
								<div class='checkbox-item' v-for='(items,indexs) in item.field' :key='indexs'>
									<div class='radio-ico' v-if='item.type=="radio"'></div>
									<div class='checkbox-ico' v-else></div>
									<div class='name'>{{ items.label }}</div>
								</div>
							</div>
							<el-select v-else-if='item.type=="select"' clearable placeholder="请选择">
								<el-option v-for="(items,indexs) in item.field" :key="indexs" :label="items.label" :value="items.value">
								</el-option>
							</el-select>
							<div class='input-box' v-else-if='item.type!=="desc"'>请选择</div>
						</div>
					</transition-group>
				</draggable>
				<div class='empty-box' v-if='!arr.length'>从左侧拖入或点选组件进行问卷设计</div>
				<div class="btn-box" v-if='arr.length>0'>
					<div class='btn' @click='submit(1)'>{{isEdit==1?'修改':'提交'}}问卷</div>
				</div>
			</div>
			<div class='right-box'>
				<div class="top-info">组件属性{{itemData?'-'+itemData.type:''}}</div>
				<div class='right-content'>
					<div class='empty-box' v-if='arr.length>0&&editIndex===""'>点击中间问卷内容进行编辑</div>
					<div v-if='editIndex!==""'>
						<div class='ico-box' @click='goElement'><i class="el-icon-link" style='color: #fff'></i></div>
						<div class='row-box'>
							<div class='title'>题目：</div>
							<el-input v-model="arr[editIndex].name" type="textarea" 
							 show-word-limit :autosize="{minRows: 2, maxRows: 15}" placeholder="请输入题目" maxlength='500'></el-input>
						</div>
						<div class='row-box' v-if='itemData.type!=="desc"'>
							<div class='title'>是否必填：</div>
							<el-switch @change='changeSwitch' v-model="arr[editIndex].isAnswer"
							  active-color="#13ce66" inactive-color="#ddd">
							</el-switch>
						</div>
						<div class='row-box' v-if='itemData.common=="input"&&itemData.type!=="idcard"&&itemData.type!=="tel"'>
							<div class='title'>字符长度：</div>
							<el-input v-model="arr[editIndex].maxNum" type="input" 
							 show-word-limit autosize placeholder="请输入(最多可输入999字)" maxlength='3'></el-input>
						</div>
						<div class='row-box' v-if='itemData.type=="image"'>
							<div class='title'>最大数量：</div>
							<el-input v-model="arr[editIndex].maxNum" type="input" 
							 show-word-limit autosize placeholder="请输入(最多可输入9,默认1)" maxlength='1'></el-input>
						</div>
						<div v-if='itemData.type=="radio"||itemData.type=="checkbox"||itemData.type=="select"'>
							<div class='row-box'>
								<div class='title'></div>
								<el-button @click='addSelect(1)' size='small' style='cursor: pointer;' type="primary" plain icon="el-icon-circle-plus-outline">添加选项</el-button>
								<el-button v-if='itemData.type=="select"' @click='dialogVisible=true' size='small' style='cursor: pointer;' type="primary" plain icon="el-icon-circle-plus-outline">批量导入</el-button>
							  <el-button v-if='itemData.field.length>1' @click='deleteAll' size='small' style='cursor: pointer;' type="info" plain icon="el-icon-delete">全部删除</el-button>
							</div>
							<div class='row-box' v-for='(item,index) in itemData.field' :key='index'>
								<div class='title'>选项{{index+1}}：</div>
								<el-input v-model="itemData.field[index].label" placeholder="请输入" maxlength='30'></el-input>
								<el-button v-if='index==0' style='margin-left: 5px;' type="info" icon="el-icon-info" size='mini' plain circle></el-button>
								<el-button v-if='index!==0' style='margin-left: 5px;' @click='deletefield(index)' size='mini' plain type="danger" icon="el-icon-delete" circle></el-button>
							</div>
						</div>
						<div v-if='itemData.type=="fill"'>
							<div class='row-box'>
								<div class='title'></div>
								<el-button @click='addSelect(2)' size='small' style='cursor: pointer;' type="primary" plain icon="el-icon-circle-plus-outline">添加输入框</el-button>
							  <el-button v-if='itemData.field.length>1' @click='deleteAll' size='small' style='cursor: pointer;' type="info" plain icon="el-icon-delete">全部删除</el-button>
							</div>
							<div class='row-box' v-for='(item,index) in itemData.field' :key='index'>
								<div class='title'>填空{{index+1}}：</div>
								<el-input v-model="itemData.field[index].label" disabled placeholder="请输入" maxlength='30'></el-input>
								<el-button v-if='index==0' style='margin-left: 5px;' type="info" icon="el-icon-info" size='mini' plain circle></el-button>
								<el-button v-if='index!==0' style='margin-left: 5px;' @click='deletefield(index)' size='mini' plain type="danger" icon="el-icon-delete" circle></el-button>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
		<el-dialog title="输入提示" :visible.sync="dialogVisible" width="40%" :close-on-click-modal='false'>
			<div style='font-size: 14px;color: #999;margin-bottom: 10px;'>注意：请从Excel复制数据粘贴至此处</div>
			<el-input v-model="selectValue" type="textarea"
			 show-word-limit :autosize="{minRows: 15, maxRows: 25}" placeholder="请输入" maxlength='1000'></el-input>
		  <span slot="footer" class="dialog-footer">
		    <el-button @click="dialogVisible=false">取 消</el-button>
		    <el-button type="primary" @click="addSelectMore">确 定</el-button>
		  </span>
		</el-dialog>
	</div>
</template>

<script>
	import draggable from 'vuedraggable'
	import { leftArr } from '../network/leftArr'
	console.log('leftArr：', leftArr)
	export default {
		name: 'home',
		components: {
			draggable,
		},
		data() {
			return {
				id: '',
				arr: [],
				//定义要被拖拽对象的数组
				leftArr: leftArr,
				moveId: -1,
				//空数组之在的样式，设置了这个样式才能拖入
				style: 'min-height: calc(100vh - 75px);display: block;',
				editIndex: '',
				itemData: null,
				input_title: '单行文本',
				textarea_title: '多行文本',
				isEdit: 0,//0提交问卷 1编辑问卷
				dialogVisible: false,
				selectValue: '',
			}
		},
		mounted(e){
			this.id = this.getQueryParam('id')
			console.log('id', this.id);
			// if(this.id){
			// 	getFormList('/getpaperquestionjson?id=' + this.id).then(res=>{
			// 		console.log('获取的数据：', res);
			// 		if(res.data.code==1){
			// 			this.arr = res.data.data.fields
			// 			if(this.arr.length>0) this.isEdit = 1
			// 			console.log('是否编辑问卷：', this.isEdit);
			// 		}
			// 	})
			// }
		},
		methods: {
			// 提交问卷
			submit(num){
				console.log(this.arr, this.leftArr)
				const isTrue = this.arr.some(item=>item.name=='')
				// 检测数组中是否存在相同的标题
				const fieldValues = this.arr.map(item => item.name);
				const isRepeat = fieldValues.some((value, index) => fieldValues.indexOf(value) !== index);
				if(isTrue){
					this.$message.error('请完善所有问卷题目！')
				}else if(isRepeat){
					//关系到后台高级事务
					this.$message.error('不能存在重复的问卷题目，请检查！')
				}else{
					if(this.isEdit==1){
						this.$confirm('此操作将修改问卷, 是否继续?', '提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: 'warning'
						}).then(() => {
							this.confirmArr(num)
						})
					}else{
						this.confirmArr(num)
					}
				}
			},
			// 确认提交问卷
			confirmArr(num){
				console.log('提交的问卷：', this.arr)
				localStorage.setItem('arr', JSON.stringify(this.arr))
				this.$router.push({path: '/preview'})
				// submitForm('/savepaperquestionjson?id=' + this.id, this.arr).then(res=>{
				// 	console.log('请求结果：', res)
				// 	if(res.data.code==1){
				// 		if(num==2){
				// 			this.$message.success('保存成功！')	
				// 			let routeData = this.$router.resolve({path: '/preview?id=' + this.id});
				// 			window.open(routeData.href, '_blank');
				// 		}else{
				// 			if(this.isEdit==1){
				// 				this.$message.success('编辑成功！')	
				// 			}else{
				// 				this.$message.success('提交成功！')	
				// 			}
				// 		}
				// 	}else{
				// 		this.$message.error('提交失败！')
				// 	}
				// })
			},
			// 解析id
			getQueryParam(param) {
				const urlParams = new URLSearchParams(window.location.search);
				return urlParams.get(param);
			},
			// 深拷贝, 避免新数据改变, 原数据也跟着改变
			cloneItem(item) {
				return JSON.parse(JSON.stringify(item))
			},
			// 删除下拉框所有选项/除第一个
			deleteAll(){
				this.$confirm('是否删除所有添加项?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.itemData.field = this.itemData.field.slice(0,1)
					this.arr[this.editIndex].field = this.itemData.field
				})
			},
			// 批量导入下拉框选项
			addSelectMore(){
				if(!this.selectValue){
					this.$message.error('输入内容不能为空！')
				}else{
					let arr = this.selectValue.split('\t\n')
					console.log(this.selectValue, arr);
					let cur_index = this.itemData.field.length 
					arr.forEach((item,index)=>{
						// 有值并且不包含空白字符
						if(item && !/^\s*$/.test(item)){
							this.itemData.field.push({
								label: item.trim().slice(0,30),
								value: cur_index+1,
								isSelect: false,
							})
						}
					})
					this.dialogVisible = false
					this.selectValue = ''
					this.arr[this.editIndex].field = this.itemData.field
				}
			},
			// 添加选项
			addSelect(num){
				const len = this.itemData.field.length+1
				console.log(len);
				if(this.itemData.type!=='select'&&len>=11){
					this.$message.error('最多添加数量10个')
					return
				}
				if(num==1){
					// 单选/多选/下拉框
					this.itemData.field.push({
						label: '选项' + len,
						value: len,
						isSelect: false,
					})
				}else if(num==2){
					//多项填空
					this.itemData.field.push({
						label: '',
						value: '',
					})
				}
				this.$message.success('添加成功！')	
				this.arr[this.editIndex].field = this.itemData.field
				console.log(this.arr[this.editIndex], this.leftArr[1].data[7]);
			},
			// 删除选项
			deletefield(index){
				this.itemData.field.splice(index, 1)
			},
			// 改变必选
			changeSwitch(e){
				console.log(e, this.arr);
			},
			onEnd(e) {
				console.log(e);
				var that=this;
				var items=this.arr.filter(function(m){
					console.log(m);
					return m.id==that.moveId
				})
			},
			// 点击左侧组件
			handleLeftItems(items){
				console.log(items, this.arr, this.leftArr);
				const itemData = JSON.parse(JSON.stringify(items))
				this.arr.push(itemData)
				this.editIndex = this.arr.length-1
				this.itemData = itemData
			},
			// 点击中间问卷
			handleCenterItems(item,index){
				console.log(item,index)
				this.editIndex = index
				this.itemData = item
			},
			// 复制某个问卷组件
			copyItem(item){
				console.log(item);
				this.arr.push(JSON.parse(JSON.stringify(item)))
			},
			// 删除某个问卷组件
			deleteItem(index){
				this.arr.splice(index, 1)
				console.log('删除', index, this.editIndex);
				this.editIndex = ''
				this.itemData = null
			},
			// 跳转到element UI
			goElement(){
				window.open('https://element.eleme.cn/#/zh-CN/component/icon', '_blank')
			},
		}
	}
</script>

<style lang='scss' scoped>
	@import '@/styles/home.scss';
</style>